package com.freesky.biz.pay.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserDtbankcustChannelvoucherSendRequest;
import com.alipay.api.response.AlipayUserDtbankcustChannelvoucherSendResponse;
import com.freesky.biz.activity.domain.TAlipayCouponDetail;
import com.freesky.biz.activity.domain.TCouponDetail;
import com.freesky.biz.pay.config.AliPayConfiguration;
import com.freesky.biz.pay.service.ICouponStockService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.utils.StringUtils;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class CouponStockServiceImpl implements ICouponStockService {

    private static final Logger logger = LoggerFactory.getLogger(CouponStockServiceImpl.class);

    @Autowired
    private WxPayService payService;

    @Autowired
    private AliPayConfiguration aliPayConfiguration;

    @Override
    public AjaxResult grantCouponsOpenId(TCouponDetail couponDetail){
        try{
            logger.info("grantCouponsOpenId:"+ JSON.toJSONString(couponDetail));

            String postUrl = this.payService.getPayBaseUrl()+"/v3/marketing/favor/users/"+couponDetail.getOpenId()+"/coupons";

            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("stock_id",couponDetail.getStockId());
            paramMap.put("out_request_no",couponDetail.getId());
            paramMap.put("appid",couponDetail.getAppId());
            if(StringUtils.isEmpty(couponDetail.getMchId())) {
                paramMap.put("stock_creator_mchid", this.payService.getConfig().getMchId());
            } else {
                paramMap.put("stock_creator_mchid", couponDetail.getMchId());
            }

            String result = this.payService.postV3(postUrl,JSON.toJSONString(paramMap));
            logger.info("grantCouponsOpenId:"+result);
            JSONObject jsonObject = JSON.parseObject(result);
            couponDetail.setCouponId(jsonObject.getString("coupon_id"));
        } catch (WxPayException wxe){
            logger.error(wxe.getCustomErrorMsg());
            wxe.printStackTrace();
            return AjaxResult.error(wxe.getCustomErrorMsg());
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作系统，系统异常");
        }
        return AjaxResult.success("操作成功!",couponDetail);
    }


    @Override
    public AjaxResult grantAlipayCoupon(TAlipayCouponDetail couponDetail) {
        try {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            certAlipayRequest.setServerUrl(aliPayConfiguration.getGatewayUrl());
            certAlipayRequest.setAppId(aliPayConfiguration.getAppId());
            certAlipayRequest.setPrivateKey(aliPayConfiguration.getPrivateKey());
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset(aliPayConfiguration.getCharset());
            certAlipayRequest.setSignType(aliPayConfiguration.getSignType());
            certAlipayRequest.setCertPath(aliPayConfiguration.getAppCertPath());
            certAlipayRequest.setAlipayPublicCertPath(aliPayConfiguration.getAlipayCertPath());
            certAlipayRequest.setRootCertPath(aliPayConfiguration.getAlipayRootCertPath());
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

            AlipayUserDtbankcustChannelvoucherSendRequest alipayUserDtbankcustChannelvoucherSendRequest = new AlipayUserDtbankcustChannelvoucherSendRequest();

            alipayUserDtbankcustChannelvoucherSendRequest.setBizContent("{" +
                    "  \"phone_id\":\""+couponDetail.getOpenId()+"\"," +
                    "  \"activity_id\":\""+couponDetail.getStockId()+"\"," +
                    "  \"out_biz_no\":\""+ SeqUtil.getSeqId() +"\"" +
                    "}");

            // 支付宝通用红包Resp:{"activityId":"ACT190CCV00515644","activityOrderId":"20220324180321ACT09393CCV00051406428","body":"{\"alipay_user_dtbankcust_channelvoucher_send_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"activity_id\":\"ACT190CCV00515644\",\"activity_order_id\":\"20220324180321ACT09393CCV00051406428\",\"discount_threshold_amt\":1001,\"discount_type\":\"reduce\",\"discount_value\":1000,\"send_amount\":1000,\"send_status\":\"SUCCESS\",\"voucher_id\":\"202203240007300293240AZCWK1F\"},\"alipay_cert_sn\":\"a7456c1d07b0d38c65d5de409b519d6b\",\"sign\":\"Mp/agpDS5+HUChJcnUnGfiKJb970ydZYNFseFji2FhFAbRFIesJIMXwnaDnBI8vSzRlQjf7GRRDTPYJlWehVmD/XrPNpbSqJK0kmi8OGgBO9vAA8vI7liq8NkenOa7wEe1RqTzjiHIRI4BHoGOPTQiugOLoUpG9vQztcso6eQXr+gCBZkBcqi0GXVbr7137aZcYQ94juZI7UjES0GYOEUbjXq2gBik8cawpT0iTkWfQk1IwHQKQ5bcjC1L4eh11LMwbyHG4zXzJo1ZUnnbIH3NqemYSTtGqcYmpBfta7wkIw7O201NnogNywX6QJ3Ry9EJMJ3BsCR2ENZYhBoIhqqQ==\"}","code":"10000","discountThresholdAmt":1001,"discountType":"reduce","discountValue":1000,"errorCode":"10000","msg":"Success","params":{"biz_content":"{  \"user_id\":\"2088512933424935\",  \"activity_id\":\"ACT190CCV00515644\",  \"out_biz_no\":\"956578649744740352\"}"},"sendAmount":1000,"sendStatus":"SUCCESS","success":true,"voucherId":"202203240007300293240AZCWK1F"}
            logger.info("支付宝通用红包Req:"+alipayUserDtbankcustChannelvoucherSendRequest.getBizContent());
            AlipayUserDtbankcustChannelvoucherSendResponse responseDt = alipayClient.certificateExecute(alipayUserDtbankcustChannelvoucherSendRequest);
            logger.info("支付宝通用红包Resp:"+ com.alibaba.fastjson.JSON.toJSONString(responseDt));

            if(responseDt.isSuccess()){
                couponDetail.setActivityOrderId(responseDt.getActivityOrderId());
                couponDetail.setVoucherId(responseDt.getVoucherId());
                couponDetail.setStatusMsg("成功");
                return AjaxResult.success("操作成功",couponDetail);
            } else {
                couponDetail.setStatusMsg("失败:"+ responseDt.getSubMsg());
                return AjaxResult.error(responseDt.getSubMsg(),couponDetail);
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作系统，系统异常");
        }

    }


}
